package org.charry.lib.commons.datetime;

import java.sql.Timestamp;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Utility class for time operation.
 * 
 * @author wcharry
 * 
 */
public final class DateTimeUtil {
	/**
	 * Log4j for DateTimeUtil.
	 */
	private static Log log = LogFactory.getLog(DateTimeUtil.class);

	/**
	 * Dummy constructor.
	 */
	private DateTimeUtil() {
		// NOOP
	}

	/**
	 * Return the time diff(mill-second) of 2 time string.
	 * 
	 * @param time1
	 *            the first time string
	 * @param time2
	 *            the second time string
	 * @return time diff(long)
	 */
	public static long getTimeDiff(final String time1, final String time2) {
		java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
				"yyyy-MM-dd hh:mm:ss", java.util.Locale.CHINESE);
		java.util.Date dt1 = null;
		java.util.Date dt2 = null;
		long value = Long.MIN_VALUE;

		try {
			dt1 = sdf.parse(time1);
			dt2 = sdf.parse(time2);
		} catch (Exception e) {
			log.error("failed to parse time1:" + time1 + ", or time2:" + time2);

			return value;
		}

		value = dt1.getTime() - dt2.getTime();

		return value;
	}

	/**
	 * Convert UNIX time stamp to java.util.Date.
	 * 
	 * @param timestamp
	 *            UNIX time stamp
	 * @return java Date instance
	 */
	public static Date toDate(final long timestamp) {
		Date date = new Date();
		Timestamp ts = new Timestamp(timestamp);
		try {
			date.setTime(ts.getTime());
		} catch (Exception e) {
			log.error(e);
		}

		return date;
	}

	/**
	 * Convert java Date to UNIX time stamp.
	 * 
	 * @param date
	 *            java Date instance
	 * @return UNIX time stamp
	 */
	public static long toTimestamp(final Date date) {
		java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());

		return timeStampDate.getTime();
	}
}
